package org.example;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket extends Thread {
    private int tickets = 0;
    //锁对象要唯一
    private Object obj = new Object();

    /*@Override
    public void run() {
        while (true) {
            //不能写在循环外面
            synchronized (obj) { // 对可能有安全问题的代码加锁,多个线程必须使用同一把锁
                if (method()) break;
            }
            //t1出来了，这段代码的锁就被释放了
        }
    }

    private boolean method() {
        //t1进来后，就会把这段代码给锁起来
        if (tickets < 100) {
            try {
                Thread.sleep(100);
                //t1休息100毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //窗口1正在出售第100张票
            System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
            tickets++; //tickets = 99;
        }else {
            return true;
        }
        return false;
    }*/


    /*锁的运用*/
    Lock lock  = new ReentrantLock();
    @Override
    public void run() {
        while (true) {
           //同步代码块
         lock.lock();
         try {
             //判断
             if (tickets == 100){
                 break;
             }else {
                 Thread.sleep(10);
                 tickets++;
                 System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
             }
         }catch (InterruptedException e){
             e.printStackTrace();
         }finally {
             lock.unlock();
         }
        }
    }
}